package com.meida.module.bus.provider.handler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.constants.ErrorCode;
import com.meida.common.mybatis.base.mapper.SuperMapper;
import com.meida.common.mybatis.interceptor.UpdateInterceptor;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.client.entity.AppUserExtra;
import com.meida.module.bus.provider.mapper.AppUserExtraMapper;
import com.meida.module.bus.provider.util.ToolsUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author lidd
 * @description: 用户扩展字段实名认证
 * @date: 2022年-06月-23日  00:06:42
 */
@Component("appUserExtraUpdateHandler")
public class AppUserExtraUpdateHandler implements UpdateInterceptor {

    @Value("${tencent.secretId}")
    private String secretId;

    @Value("${tencent.secretKey}")
    private String secretKey;

    @Value("${tencent.verifyIdcardUrl}")
    private String verifyIdcardUrl;

    @Value("${tencent.verifyIdcardSwitch}")
    private String verifyIdcardSwitch;

    @Resource
    private AppUserExtraMapper mapper;

    @Override
    public ResultBody validate(CriteriaUpdate cu, EntityMap params) {
        if ("on".equals(verifyIdcardSwitch) && !ToolsUtil.verifyIdcard(secretId, secretKey, params.get("fullName"), params.get("idCard"), verifyIdcardUrl)) {
            return new ResultBody().code(ErrorCode.ERROR.getCode()).setMsg("请核对认证信息");
        }
        return ResultBody.ok();
    }

    @Override
    public void prepare(CriteriaUpdate cu, EntityMap params, Object o) {

        cu.eq(true, "userId", OpenHelper.getUserId());
        cu.set(ObjectUtil.isNotNull(params.get("fullName")), "fullName", params.get("fullName"));
        cu.set(ObjectUtil.isNotNull(params.get("idCard")), "idCard", params.get("idCard"));
        cu.set(true, "issueDate", DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN));


    }


    @Override
    public Object getEntity(CriteriaUpdate cu, EntityMap params) {

        AppUserExtra appUserExtra = (AppUserExtra) cu.getEntity(AppUserExtra.class);
        //appUserExtra.setFullName(params.get("fullName"));
        //appUserExtra.setIdCard(params.get("idCard"));
        //appUserExtra.setIssueDate(DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN));
        //appUserExtra.setUserId( OpenHelper.getUserId());

        return appUserExtra;
    }


    /**
     * 获取自定义Mapper
     *
     * @return
     */
    @Override
    public SuperMapper getMapper() {
        return mapper;
    }
}
